<template>
    <navigation></navigation>
    <div class="min-h-screen bg-gray-100">
        <div class="bg-blue-500 text-white py-8 text-center">
            <div class="flex justify-center items-center mb-4">
                <div class="rounded-full bg-white w-24 h-24 flex items-center justify-center">
                    <span class="text-blue-500 text-2xl font-bold">签到</span>
                </div>
            </div>
            <p class="text-xl">连续打卡 {{ consecutiveDays }} 天</p>
        </div>

        <div class="max-w-2xl mx-auto bg-white shadow-lg rounded-lg overflow-hidden my-8">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6">
                    <button @click="changeMonth(-1)" class="text-gray-600 hover:text-gray-800">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                    </button>
                    <h2 class="text-xl font-bold">{{ currentYear }}年{{ currentMonth }}月</h2>
                    <button @click="changeMonth(1)" class="text-gray-600 hover:text-gray-800">
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </button>
                </div>
                <div class="grid grid-cols-7 gap-2 text-center">
                    <div v-for="day in weekDays" :key="day" class="font-medium text-gray-500">{{ day }}</div>
                    <div v-for="day in calendarDays" :key="day.date" class="p-2 relative"
                        :class="{ 'bg-blue-100 rounded-full': isToday(day.date) }">
                        <span :class="{ 'text-gray-400': !day.isCurrentMonth }">{{ day.date.getDate() }}</span>
                        <div v-if="isCheckedIn(day.date)"
                            class="absolute bottom-0 left-1/2 transform -translate-x-1/2 w-1 h-1 bg-blue-500 rounded-full">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="text-center mb-8">
            <button @click="checkIn" :disabled="isCheckedInToday"
                class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition duration-300 ease-in-out transform hover:scale-105 !rounded-button whitespace-nowrap"
                :class="{ 'cursor-not-allowed opacity-75': isCheckedInToday }">
                {{ isCheckedInToday ? '今日已签到' : '立即签到' }}
            </button>
        </div>

        <p class="text-center text-gray-600">{{ message }}</p>
    </div>
</template>

<script setup>
// 引入依赖
import { ref, computed, onMounted } from 'vue';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import navigation from '../../views/navigation.vue';
import { getSignInRecordList, postSignIn } from '@/api/student/signIn/signIn';

// 定义初始状态
const currentDate = ref(new Date());
const checkedInDates = ref([]);
const consecutiveDays = ref(0);
const message = ref('');

// 定义周一到周日的天数名称
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 计算当前年份
const currentYear = computed(() => currentDate.value.getFullYear());
// 计算当前月份
const currentMonth = computed(() => currentDate.value.getMonth() + 1);

// 计算日历显示的日期区间
const calendarDays = computed(() => {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);

    const days = [];
    const prevMonthDays = firstDay.getDay();
    const nextMonthDays = 6 - lastDay.getDay();

    // 前一个月的日期
    for (let i = prevMonthDays; i > 0; i--) {
        const date = new Date(year, month, -i + 1);
        days.push({ date, isCurrentMonth: false });
    }

    // 当前月的日期
    for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i);
        days.push({ date, isCurrentMonth: true });
    }

    // 下一个月的日期
    for (let i = 1; i <= nextMonthDays; i++) {
        const date = new Date(year, month + 1, i);
        days.push({ date, isCurrentMonth: false });
    }

    return days;
});

// 判断今天是否已经签到
const isCheckedInToday = computed(() => {
    const today = new Date();
    return checkedInDates.value.some(date =>
        date.getDate() === today.getDate() &&
        date.getMonth() === today.getMonth() &&
        date.getFullYear() === today.getFullYear()
    );
});

// 改变展示的月份
function changeMonth(delta) {
    currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + delta, 1);
}

// 判断传入的日期是否是今天
function isToday(date) {
    const today = new Date();
    return date.getDate() === today.getDate() &&
        date.getMonth() === today.getMonth() &&
        date.getFullYear() === today.getFullYear();
}

// 判断传入的日期是否已签到
function isCheckedIn(date) {
    return checkedInDates.value.some(checkedDate =>
        checkedDate.getDate() === date.getDate() &&
        checkedDate.getMonth() === date.getMonth() &&
        checkedDate.getFullYear() === date.getFullYear()
    );
}

// 更新 message 的值
function updateMessage() {
    if (isCheckedInToday.value) {
        message.value = '今日已签到，明天也要加油哦！';
    } else {
        message.value = '今天还没有签到哦，快来打卡吧！';
    }
}

onMounted(async () => {
    try {
        const res = await getSignInRecordList();
        console.log("res:", res);
        // 处理带时间的日期字符串
        checkedInDates.value = res.map(dateStr => {
            const [datePart] = dateStr.createTime.split(' ');
            const [year, month, day] = datePart.split('-').map(Number);
            return new Date(year, month - 1, day);
        });
        // 过滤未来日期和无效日期
        const today = new Date();
        checkedInDates.value = checkedInDates.value.filter(date => date <= today);
        updateConsecutiveDays();
        updateMessage(); // 更新 message
    } catch (error) {
        console.error('获取签到记录失败:', error);
        message.value = '获取签到记录失败，请稍后重试';
    }
});

// 修改后的签到函数（示例，根据实际接口调整）
async function checkIn() {
    if (!isCheckedInToday.value) {
        // 网络检查
        if (!navigator.onLine) {
            message.value = '当前网络不可用，请稍后重试！';
            return;
        }
        try {
            // 调用签到接口
            const res = await postSignIn();
            const today = new Date();
            checkedInDates.value.push(today); // 添加今天的签到记录
            updateConsecutiveDays(); // 更新连续签到天数
            message.value = '签到成功！今天也要元气满满哦！';
            updateMessage(); // 更新 message
        } catch (error) {
            console.error('签到失败:', error);
            message.value = '签到失败，请检查网络连接';
        }
    } else {
        message.value = '今天已经签到过啦，明天再来哦！';
        updateMessage(); // 更新 message
    }
}

// 更新连续签到天数
function updateConsecutiveDays() {
    // 将日期转换为YYYY-MM-DD格式并去重
    const dateSet = new Set();
    checkedInDates.value.forEach(date => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        dateSet.add(`${y}-${m}-${d}`);
    });
    const sortedDates = Array.from(dateSet).sort((a, b) => b.localeCompare(a)); // 从新到旧排序

    let count = 0;
    let currentStreak = 0;
    let prevDate = null;

    for (const dateStr of sortedDates) {
        const currentDate = new Date(dateStr);
        currentDate.setHours(0, 0, 0, 0);

        if (prevDate === null) {
            currentStreak = 1;
            prevDate = currentDate;
        } else {
            const prevDay = new Date(prevDate);
            prevDay.setDate(prevDay.getDate() - 1);
            prevDay.setHours(0, 0, 0, 0);

            if (currentDate.getTime() === prevDay.getTime()) {
                currentStreak++;
            } else {
                break;
            }
            prevDate = currentDate;
        }

        if (currentStreak > count) {
            count = currentStreak;
        }
    }

    consecutiveDays.value = count;
}

// 初始化时更新 message
updateMessage();
</script>

<style scoped>
/* 自定义样式 */
.calendar-day {
    @apply w-10 h-10 flex items-center justify-center rounded-full transition-colors duration-200 ease-in-out;
}

.calendar-day:hover {
    @apply bg-blue-100;
}

.calendar-day.checked {
    @apply bg-blue-500 text-white;
}

.calendar-day.checked {
    @apply bg-green-500 text-white; /* 使用绿色表示签到成功 */
}
</style>